package com.d3works.apps.cash.management.db.repo;

import com.d3works.apps.base.db.Company;
import com.d3works.apps.base.db.repo.SequenceRepository;
import com.d3works.apps.base.service.administration.SequenceService;
import com.d3works.apps.cash.management.db.ForecastRecap;
import com.d3works.apps.cash.management.exception.CashManagementExceptionMessage;
import com.d3works.exception.D3worksException;
import com.d3works.exception.db.repo.TraceBackRepository;
import com.d3works.exception.service.TraceBackService;
import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;
import java.math.BigDecimal;
import javax.persistence.PersistenceException;

public class CashManagementForecastRecapRepository extends ForecastRecapRepository {

  @Override
  public ForecastRecap save(ForecastRecap entity) {

    try {

      if (entity.getForecastRecapSeq() == null) {
        Company company = entity.getCompany();

        String sequence =
            Beans.get(SequenceService.class)
                .getSequenceNumber(
                    SequenceRepository.FORECAST_RECAP_SEQUENCE,
                    company,
                    ForecastRecap.class,
                    "forecastRecapSeq");

        if (sequence == null) {
          throw new D3worksException(
              company,
              TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
              I18n.get(CashManagementExceptionMessage.FORCAST_RECAP_SEQUENCE_ERROR),
              company.getName());

        } else {
          entity.setForecastRecapSeq(sequence);
        }
      }

      return super.save(entity);
    } catch (D3worksException e) {
      TraceBackService.traceExceptionFromSaveMethod(e);
      throw new PersistenceException(e.getMessage(), e);
    }
  }

  @Override
  public ForecastRecap copy(ForecastRecap entity, boolean deep) {

    ForecastRecap copy = super.copy(entity, deep);

    copy.clearForecastRecapLineList();
    copy.setCalculationDate(null);
    copy.setForecastRecapSeq(null);
    copy.setEndingBalance(BigDecimal.ZERO);
    return copy;
  }
}
